package com.malou.client.seguridad.usuario;

import java.util.Arrays;

import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.data.ModelIconProvider;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.extjs.gxt.ui.client.widget.treegrid.TreeGrid;
import com.extjs.gxt.ui.client.widget.treegrid.TreeGridCellRenderer;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.malou.client.MalouConstants;
import com.malou.client.MalouMessages;
import com.malou.client.seguridad.menu.MenuPanel;
import com.malou.client.seguridad.menu.Menus;
public class UsuarioPanel extends VerticalPanel {
	
	private MalouConstants constants = GWT.create(MalouConstants.class);
	private MalouMessages messages = GWT.create(MalouMessages.class);
	private TreeGrid<Usuario> tree;
	private MenuItem insert;
	private MenuItem keys;
	private MenuItem editRol;
	private MenuItem user;
	private MenuItem remove;
	private MenuItem edit;
	private GrupoDialog dialog;
	private UsuarioDialog dialogUser;
	private RolesDialog dialogRoles;
	private Usuario selectedModel;
	public MenuPanel menuPanel;
	
	public UsuarioPanel(){
		
		Usuarios.list();
		
		setLayout(new FitLayout());
        addStyleName("fondo-blanco");
        setBorders(true);
        setScrollMode(Scroll.AUTOY);
                
        ColumnConfig usuario = new ColumnConfig("usuario", "Usuario", 200);  
        usuario.setRenderer(new TreeGridCellRenderer<Usuario>());
        
        ColumnConfig nombres = new ColumnConfig("nombres", "Nombres", 200);
        ColumnConfig apellidos = new ColumnConfig("apellidos", "Apellidos", 200);
        ColumnConfig tienda = new ColumnConfig("tienda", "Tienda", 50);
        ColumnConfig privilegio = new ColumnConfig("privilegio", "Privilegio", 100);
        
        ColumnModel cm = new ColumnModel(Arrays.asList(usuario, nombres, apellidos, tienda, privilegio));
        
        tree = new TreeGrid<Usuario>(Usuarios.store, cm);  
        tree.setStateful(true);
        //tree.setSize(800,200);
        tree.setWidth(800);
        tree.getTreeView().setBufferEnabled(false);
        tree.setAutoHeight(true);
        tree.setAutoExpandColumn("usuario");
        
        tree.setIconProvider(new ModelIconProvider<Usuario>() {
  	      public AbstractImagePrototype getIcon(Usuario model) {
  	    	  
  	    	  Boolean hasChildren = model.getHaschildren();  	    	  
  	    	  String nombres = model.getNombres();
  	    	  if (hasChildren != null){
    			  //si tiene hijos    			 
  	    			return IconHelper.createPath("images/icons/people.png");
    		  }
    		  else{
    			  if(nombres != null)
    				  return IconHelper.createPath("images/icons/user.png");
    			  else
    				  return IconHelper.createPath("images/icons/people.png");
    		  }  	    	     
  	      }
  	    });
        
        add(tree);
        
        dialog = new GrupoDialog();        
		dialog.usuarioPanel = this;
		dialog.setStore(Usuarios.store);
		
		dialogUser = new UsuarioDialog();        
		dialogUser.usuarioPanel = this;
		dialogUser.setStore(Usuarios.store);
		
		dialogRoles = new RolesDialog();        
		dialogRoles.usuarioPanel = this;
		dialogRoles.setStore(Usuarios.store);		
		
        Menu contextMenu = new Menu();
        
        insert = new MenuItem();  
	    insert.setText(constants.usuarioAgregarGrupo());
	    insert.setId("insert");
	    insert.setIcon(IconHelper.createStyle("icon-group"));  
	    insert.addSelectionListener(new SelectionListener<MenuEvent>() {  
	      public void componentSelected(MenuEvent ce) {
	    	  Usuario selectedModel = tree.getSelectionModel().getSelectedItem();
	    	  dialog.beforeAdd();
	    	  dialog.reset();
	    	  dialog.unbind();
	    	  dialog.parent_id.setValue(selectedModel.getId().toString());	    	  
	    	  dialog.show();	    	 
	      }  
	    });  
	    contextMenu.add(insert);
	    
	    user = new MenuItem();  
	    user.setText(constants.usuarioAgregarUsuario());
	    user.setId("user");
	    user.setIcon(IconHelper.createStyle("user"));  
	    user.addSelectionListener(new SelectionListener<MenuEvent>() {  
	      public void componentSelected(MenuEvent ce) {
	    	  Usuario selectedModel = tree.getSelectionModel().getSelectedItem();
	    	  dialogUser.beforeAdd();
	    	  dialogUser.reset();
	    	  dialogUser.unbind();
	    	  dialogUser.parent_id.setValue(selectedModel.getId().toString());	    	  
	    	  dialogUser.show();	  	 
	      }  
	    });  
	    contextMenu.add(user);
	    
	    edit = new MenuItem();  
	    edit.setText(constants.editar());
	    edit.setId("edit");
	    edit.setIcon(IconHelper.createStyle("icon-update"));  
	    edit.addSelectionListener(new SelectionListener<MenuEvent>() {  
	      public void componentSelected(MenuEvent ce) {
	    	  Usuario selectedModel = tree.getSelectionModel().getSelectedItem();
	    	  String nombres = selectedModel.getNombres();
	    	  if(nombres != null){
	    		  dialogUser.bind(selectedModel);	    	  
	    		  dialogUser.beforeEdit();  
	    		  dialogUser.show();
	    	  }else{
	    		  dialog.bind(selectedModel);	    	  
	    		  dialog.beforeEdit();  
	    		  dialog.show();
	    	  }
	      }  
	    });
	    
	    contextMenu.add(edit);
	    
	    keys = new MenuItem();  
	    keys.setText(constants.usuarioCambiarClave());
	    keys.setId("edit");
	    keys.setIcon(IconHelper.createStyle("icon-password"));  
	    keys.addSelectionListener(new SelectionListener<MenuEvent>() {  
	      public void componentSelected(MenuEvent ce) {
	    	  Usuario selectedModel = tree.getSelectionModel().getSelectedItem();    	  
	    	  
	    	  dialogUser.bind(selectedModel);	    	  
	    	  dialogUser.beforeChangePassword();  
	    	  dialogUser.show();
	    	  
	      }  
	    });
	    
	    contextMenu.add(keys);
	    
	    editRol = new MenuItem();  
	    editRol.setText(constants.usuarioModificarGrupo());
	    editRol.setId("edit");
	    editRol.setIcon(IconHelper.createStyle("icon-users-edit"));  
	    editRol.addSelectionListener(new SelectionListener<MenuEvent>() {  
	      public void componentSelected(MenuEvent ce) {
	    	  Usuario selectedModel = tree.getSelectionModel().getSelectedItem();
	    	   //System.out.println("click "+selectedModel.get("id"));   	  
	    	  dialogRoles.bind(selectedModel);
	    	  dialogRoles.clear();
	    	  dialogRoles.getButtonBar().disable();
	    	  dialogRoles.show();
	    	  //dialogRoles.setChecked();
	    	  
	      }  
	    });
	    
	    contextMenu.add(editRol);
	    
	    final Listener<MessageBoxEvent> l = new Listener<MessageBoxEvent>() {  
	          public void handleEvent(MessageBoxEvent ce) {  
	            String button_id = ce.getButtonClicked().getItemId();  
	             if(Dialog.YES == button_id){	        		 
	            	 if(selectedModel != null){
	            		 Integer id = selectedModel.get("id");
	            		 Integer rol_id = selectedModel.getParent_id();	            		
	            		 String nombres = selectedModel.getNombres();
	       	    	  	 if(nombres != null)
	       	    	  		 Usuarios.deleteUser(id,rol_id);
	       	    	     else
	       	    	    	 Usuarios.deleteGroup(id);
	            	 }
	            }
	         }  
	    };
	    
	    remove = new MenuItem();  
	    remove.setText(constants.eliminar());
	    remove.setId("remove");
	    remove.setIcon(IconHelper.createStyle("icon-delete"));  
	    remove.addSelectionListener(new SelectionListener<MenuEvent>() {  
	      public void componentSelected(MenuEvent ce) {
	    	  selectedModel = tree.getSelectionModel().getSelectedItem();
	    	  String mensaje="";
	    	  if(selectedModel.getNombres() == null)
	    		  mensaje = messages.usuarioEstaSeguroRol(selectedModel.getUsuario());
	    	  else
	    		  mensaje = messages.usuarioEstaSeguro(selectedModel.getUsuario());
	    	  
	    	  MessageBox.confirm(constants.confirmacion(), mensaje, l).getDialog().getButtonById(Dialog.YES).setText(constants.si());
	    	  	    	  
	      }  
	    });
	    
	    contextMenu.add(remove);
        
        MenuItem reload = new MenuItem();  
	    reload.setText(constants.actualizar());
	    reload.setId("reload-users");
	    reload.setIcon(IconHelper.createStyle("x-tbar-refresh"));  
	    reload.addSelectionListener(new SelectionListener<MenuEvent>() {  
	      public void componentSelected(MenuEvent ce) {
	    	  Usuarios.loader.load();
	      }  
	    });  
	    contextMenu.add(reload); 
	  
	    tree.setContextMenu(contextMenu);
	    tree.addListener(Events.OnContextMenu, new Listener<BaseEvent>(){

			@Override
			public void handleEvent(BaseEvent be) {
				if(tree.getSelectionModel().getSelectedItem() == null){
					remove.setEnabled(false);
					edit.setEnabled(false);
					user.setEnabled(false);
					insert.setEnabled(true);
					keys.setEnabled(false);
					editRol.setEnabled(false);
				}
			}			
        	
        });
	
	    tree.getSelectionModel().addSelectionChangedListener(new SelectionChangedListener<Usuario>() {
			
			@Override
			public void selectionChanged(SelectionChangedEvent<Usuario> se) {
				if(se.getSelectedItem() != null){					
					Usuario u = se.getSelectedItem();					
					if(u.getIdprivilegio() == null || u.getIdprivilegio()==2){						
						menuPanel.tree.setCheckable(true);					
						menuPanel.tree.setCheckStyle(CheckCascade.NONE);
						
						Menus.usuario_id = u.getId();
						String name = u.getNombres();
						if(name == null)
							Menus.tipo = 1; //rol
						else
							Menus.tipo = 2; //usuario
						
						menuPanel.guardarPermiso.setEnabled(false);
						Menus.getMenusArray();
						//usuario
						if(u.getNombres() != null){
							user.setEnabled(false);
							insert.setEnabled(false);
							keys.setEnabled(true);
							editRol.setEnabled(true);							
							Usuarios.user_id = u.getId();							
						}else{//rol
							user.setEnabled(true);
							insert.setEnabled(true);
							keys.setEnabled(false);
							editRol.setEnabled(false);							
						}
						remove.setEnabled(true);
						edit.setEnabled(true);
					}else{//super Usuario privilegio: 1
						Menus.getMenusArray();
						menuPanel.tree.setCheckable(false);						
						menuPanel.guardarPermiso.setEnabled(false);
						
						user.setEnabled(false);
						insert.setEnabled(false);
						keys.setEnabled(true);
						editRol.setEnabled(true);
						
						Usuarios.user_id = u.getId();						
					}
				}else{
					menuPanel.tree.setCheckable(false);					
					menuPanel.guardarPermiso.setEnabled(false);
					
					Menus.usuario_id=null;
					Menus.tipo=null;
					Menus.getMenusArray();
				}
			}
		});
	    
	    Menu contextMenuRaiz = new Menu();
	    
	    MenuItem add = new MenuItem();  
	    add.setText(constants.usuarioAgregarGrupo());
	    add.setId("insert");
	    add.setIcon(IconHelper.createStyle("icon-group"));  
	    add.addSelectionListener(new SelectionListener<MenuEvent>() {  
	      public void componentSelected(MenuEvent ce) {
	    	  dialog.beforeAdd();
	    	  dialog.reset();
	    	  dialog.unbind();	    	  
	    	  dialog.show();
	      }  
	    });  
	    contextMenuRaiz.add(add);
	    
	    reload = new MenuItem();  
	    reload.setText(constants.actualizar());
	    reload.setId("reload-users");
	    reload.setIcon(IconHelper.createStyle("x-tbar-refresh"));  
	    reload.addSelectionListener(new SelectionListener<MenuEvent>() {  
	      public void componentSelected(MenuEvent ce) {
	    	  Usuarios.loader.load();
	      }  
	    });  
	    contextMenuRaiz.add(reload);
	    
	    setContextMenu(contextMenuRaiz);
	    
	    addListener(Events.OnContextMenu, new Listener<BaseEvent>(){

			@Override
			public void handleEvent(BaseEvent be) {
				tree.getSelectionModel().deselectAll();				
			}			
        	
        });
        
	}
}
